#include <SelectNetDialog.h>
#include <pcap.h>
#include <QtGui>

SelectNetDialog::SelectNetDialog(QWidget *parent):QDialog(parent)
{
	ui.setupUi(this);
	this->setFont(QApplication::font());
	
	ui.tableWidget->setColumnWidth(0,300);
	ui.tableWidget->setColumnWidth(1,120);
	
	pcap_if_t* alldevs;
	pcap_if_t* d;
	char errbuf[PCAP_ERRBUF_SIZE];
	pcap_findalldevs(&alldevs,errbuf); //获得网络设备指针
	int count=0;
	ui.tableWidget->clearContents();
	for(d=alldevs;d;d=d->next) //枚举网卡然后添加到ComboBox中
	{
		ui.tableWidget->setRowCount(count+1);
		ui.tableWidget->setItem(count,0,new QTableWidgetItem(d->name));
		bpf_u_int32 netp,maskp;
		if(pcap_lookupnet(d->name,&netp,&maskp,errbuf)!=-1){
			unsigned char *p=(unsigned char *)&netp;
			char buf[16];
			sprintf(buf,"%d.%d.%d.%d",p[0],p[1],p[2],p[3]);
			ui.tableWidget->setItem(count,1,new QTableWidgetItem(buf));
			printf(buf);printf("\n");
		}
		count++;
	}
	pcap_freealldevs(alldevs); //释放alldev资源
}

void SelectNetDialog::on_pushButton_clicked()
{
	QList<QTableWidgetItem *> tbi=ui.tableWidget->selectedItems ();
	QSettings settings("ShadaLinux", "ShadaArp");
	settings.setValue("net",tbi[0]->text());
	settings.sync();
	printf(tbi[0]->text().toStdString().c_str());
	printf("Selected.\n");
	this->close();
}
